package com.milk.servlet;

import com.milk.Dao.EmployeesDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取用户名和密码参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 调用 EmployeesDao 的方法进行注册
        int result = EmployeesDao.registerEmployee(username, password);

        // 根据注册结果重定向到登录页面并传递错误信息
        if (result > 0) {
            // 注册成功，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } else if (result == -2) {
            // 用户名已存在，重定向到登录页面并传递错误信息
            response.sendRedirect(request.getContextPath() + "/login.jsp?error=exists");
        } else {
            // 注册失败，重定向到登录页面并传递错误信息
            response.sendRedirect(request.getContextPath() + "/login.jsp?error=failed");
        }
    }
}